#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@File Name  : root_class.py
@Author     : LeeCQ
@Date-Time  : 2019/11/30 19:27

"""

import requests
import tempfile
import json
from bs4 import BeautifulSoup

__all__ = ['Root9C']


class Root9C:
    """
    这个类里面应该包含9CCMS的基础 方法 & 字段 & 属性；


    """
    DIR_TEMP = tempfile.gettempdir()
    DIR_SUP = r'D:\phpstudy_pro\WWW\9c\JCSQL\Home/'  # 一定要有"/"
    DIR_ROOT = r'D:\temp_9c/'

    HOST = 'http://9c.local'
    HEADER = {
            'Accept': 'text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-Hans-CN, zh-Hans; q=0.5',
            'Cache-Control': 'max-age=0',
            'Connection': 'Keep-Alive',
            'Host': '',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'
        }

    def create_HEADERS(self, url):
        _h = self.HEADER
        _h['Host'] = url.split('/')[2]
        return _h

    def set_dir_sup(self, sup):
        self.DIR_SUP = sup

    def set_dir_root(self, root_dir):
        self.DIR_ROOT = root_dir

    def get_http_page(self, url, header):
        """
        获取网页源码；
        :return: 返回一个bs4处理过的 BeautifulSoup() 对象。
        """
        header['Host'] = self.HOST
        if url.split('/')[0].upper() != 'HTTP:':
            url = 'http://' + url
        _response = requests.get(url, headers=header)
        return BeautifulSoup(_response.text, 'lxml')

    def txt2tag(self):
        """
        对sup/*.txt文件的编号和tag对应。
        :return: ((txt_path, tag),)
        """
        index = self.get_http_page(self.HOST, self.HEADER)
        tags = index.select('div.menu-tag > ul > li > ul > li > a')
        print(tags)
        _txt2tag = []
        for tag in tags:
            _tmp = tag.get('href').split('=')[1].split('*')
            file_name = _tmp[1] + '.txt'
            _txt2tag.append((_tmp[0], tag.text, file_name, _tmp[1]))  # kind(大分类), 标签名, txt文件名, 标签代码(a_type)
        return _txt2tag

    @staticmethod
    def json_one_txt(txt_path):
        """解析一个txt文件中的json数据
        :return JSON对象
        """
        return json.loads(open(txt_path, 'r', encoding='utf8').read())

    def json_all_txt(self, txt_path_list):
        """解析一个队列txt为json对象"""
        _temp = []
        for _t in txt_path_list:
            _temp.extend(self.json_one_txt(_t))
        return _temp

    def api_(self):
        return self.json_one_txt(self.DIR_SUP + 'API.CEY')


if __name__ == '__main__':
    r = Root9C()
    print(r.txt2tag())

